package com.storeroompda.controlview;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.EditText;
import com.storeroompda.R;
import com.storeroompda.bean.NameEvent;
import org.greenrobot.eventbus.EventBus;

/**
 * 有搜索的Edittext
 *
 */
public class EditTextWithSearchButton extends EditText {//AppCompatEditText
	public  String tag = "EditTextWithSearchButton";
	private Drawable imgSearch;
	private Context mContext;

	public EditTextWithSearchButton(Context context) {
		super(context);
		mContext = context;
		init();
	}

	public EditTextWithSearchButton(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mContext = context;
		init();
	}

	public EditTextWithSearchButton(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		init();
	}
	
	private void init() {
		imgSearch = mContext.getResources().getDrawable(R.mipmap.icon_search);
		addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if(s.toString().length()!=0) {
					NameEvent nameEvent= new NameEvent(s.toString());
					EventBus.getDefault().post(nameEvent);
				}
				else if(s.toString().length()==0) {
					NameEvent nameEvent= new NameEvent("");
					EventBus.getDefault().post(nameEvent);
				}
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			@Override
			public void afterTextChanged(Editable s) {
				setDrawable();
			}
		});
		setDrawable();
	}
	
	//����ɾ��ͼƬ
	private void setDrawable() {
			setCompoundDrawablesWithIntrinsicBounds(imgSearch, null, null, null);
	}
	
	 // ����ɾ���¼�
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (imgSearch != null && event.getAction() == MotionEvent.ACTION_UP) {
			int eventX = (int) event.getRawX();
			int eventY = (int) event.getRawY();

			Rect rect1 = new Rect();
			getGlobalVisibleRect(rect1);
			rect1.right = rect1.left + 50;
//			if(rect1.contains(eventX, eventY))
//			{
//				Log.e(tag, "onTouchEvent");
//				Intent intent = new Intent();
//				intent.setAction(Constant.searchdata);
//				mContext.sendBroadcast(intent);
//			}
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
    }

}
